package com.demo.invalidate;

import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;


public class AsyncImageDownloader {

	private Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();

	public void loadImage(final String imageUrl) {
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Drawable> softReference = imageCache.get(imageUrl);
			if(softReference.get() != null) {
				imageCallback.imageLoaded(softReference.get());
				return;
			}
		}
		
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				imageCallback.imageLoaded((Drawable)msg.obj);
			}
		};
		
		new Thread() {
			public void run() {
				Drawable drawable = loadImageFromUrl(imageUrl);
				imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
				Message msg = handler.obtainMessage(0,drawable);
				handler.sendMessage(msg);
			}
		}.start();
	}

	protected Drawable loadImageFromUrl(String imageUrl) {
		try {
			return Drawable.createFromStream(new URL(imageUrl).openStream(), "src");	
		} catch (Exception e) {
			throw new RuntimeException();
		}
	};

	private ImageCallbackListener imageCallback;
	
	public void setImageCallback(ImageCallbackListener imageCallback) {
		this.imageCallback = imageCallback;
	}

	public interface ImageCallbackListener {
		public void imageLoaded(Drawable imageDrawable);
	}
}
